import { inject, onMounted, onUnmounted } from 'vue';

const None = () => {};

const NoEnableResult = {
  popup: {
    open: None,
    hide: None,
    close: None,
    destroy: None,
    setData: None,
  },
};

function usePopupManage(config) {
  const { namespace, items } = config || {};
  const popupContext = inject('PopupContext');

  if (!popupContext.enable) {
    console.error('<PopupProvider /> 组件没有在全局挂载！');
    return NoEnableResult;
  }

  onMounted(() => {
    if (!namespace || !items) return;
    popupContext.setNamespace(namespace); // 设置当前的命名空间
    popupContext.register(items);
  });

  onUnmounted(() => {
    if (!namespace) return;
    popupContext.unregister(namespace);
  });

  return {
    elements: popupContext.elements,
    popup: {
      setProps: popupContext.setProps,
      open: popupContext.open,
      hide: popupContext.hide,
      close: popupContext.close,
      toggle: popupContext.toggle,
      destroy: popupContext.destroy,
      focus: popupContext.focus,
    },
  };
}

export default usePopupManage;
